
<template>
    <div >
        <el-container>
            <el-main   class="loginbg">
                <div class="materialContainer " >
                    <div class="box">
                        <el-form @submit.prevent="submitForm"  ref="loginFormRef" v-if="isLogin" :model="loginForm" :rules="loginRules">
                            <div class="title" v-if="isLogin">普通管理员登录</div>
                            <el-form-item  prop="username" class="input">
                                    <label  :style="usernameLabelStyles" for="name">用户名</label>
                                    <input
                                            v-model="loginForm.username"
                                            type="text"
                                            name="name"
                                            id="name"
                                            @focus="usernameOnFocus"
                                            @blur="usernameOnBlur"
                                    >
                                    <span class="spin" :style="{ width: usernameSpinWidth }"></span>
                            </el-form-item>
                            <el-form-item prop="userpass" class="input">
                                    <label :style="userpassLabelStyles" for="pass">密码</label>
                                    <input
                                            v-model="loginForm.userpass"
                                            type="password"
                                            name="pass"
                                            id="pass"
                                            @focus="userpassOnFocus"
                                            @blur="userpassOnBlur"
                                    >
                                    <span class="spin"  :style="{ width: userpassSpinWidth }"></span>
                            </el-form-item>
                            <el-form-item class="input " >
                                <label class="codelabel" :style="codeLabelStyles" for="code">验证码</label>
                                <input
                                        v-model="loginForm.code"
                                        type="text"
                                        name="code"
                                        id="code"
                                        @focus="codeOnFocus"
                                        @blur="codeOnBlur"
                                >
                                <span class="spin" id="codeSpin" :style="{ width: codeSpinWidth }"></span>
                                <div
                                        class="codeSpin" @click="refreshCode"
                                >
                                    <!-- 使用验证码组件 -->
                                    <SIdentify :identifyCode="identifyCode"></SIdentify>
                                </div>
                            </el-form-item>

                            <el-form-item class="button login">
                                    <button @click="submitForm">
                                        <span>登录</span>
                                    </button>
                            </el-form-item>
                        </el-form>
                        <a  class="loginvip" @click="loginvip" style="cursor: pointer;color: red;">我是超级管理员</a>
                        <!--                                忘记密码模态框的连接标签-->
                            <a  class="pass-forgot" @click="openForgotPasswordModal" style="cursor: pointer">忘记密码？</a>

                    </div>
<!--                            "跳转到注册页面"-->
                    <div class="overbox">
                        <div
                                class="material-button alt-2"
                                @click="toRegister"
                        >
                            <span class="shape" ></span>
                        </div>
                    </div>
                </div>
            </el-main>
        </el-container>
        <!-- 忘记密码模态框 -->
        <el-dialog
                v-if="isModalVisible"
                title="修改密码"
                v-model="isModalVisible"
                width="35%"
                @close="isModalVisible = false"
                class="custom-modal"
        >
            <el-form
                    :model="forgotPasswordForm"
                    :rules="forgotPasswordRules"
                    ref="forgotPasswordFormRef"
                    class="custom-form"
            >
                <!-- 输入邮箱或其他用于找回密码的信息 -->
                <el-form-item prop="email" label="邮箱：" class="form-item-align">
                    <el-input v-model="forgotPasswordForm.email" placeholder="请输入注册邮箱" style="width: 100%;"></el-input>
                </el-form-item>
                <el-form-item prop="userpass" label="新密码：" class="form-item-align">
                    <el-input type="password" v-model="forgotPasswordForm.userpass" placeholder="输入新密码" style="width: 100%;"></el-input>
                </el-form-item>
                <el-form-item prop="confirmPassword" label="确认密码:" class="form-item-align">
                    <el-input type="password" v-model="forgotPasswordForm.confirmPassword" placeholder="确认新密码" style="width: 100%;"></el-input>
                </el-form-item>
                <!-- 邮箱验证码 -->
                <el-form-item prop="emailcode" label="验证码：" class="flex-row form-item-align">
                    <el-input v-model="forgotPasswordForm.code" placeholder="请输入邮箱验证码"  style="width: 60%;"></el-input>
                    <el-button
                            type="primary"
                            plain
                            style="width: 38%;"
                            :disabled="disabled"
                            @click="sendEmailCode">
                        {{ msg }}
                    </el-button>
                </el-form-item>
                <el-row  :error="!rAgree ? '请先同意修改密码准则' : ''">
                    <el-checkbox
                            class="checkBox"
                            v-model="rAgree"
                            label="我同意"
                            name="type"
                    />
                    <a href="http://localhost:8081/updaterole" target="_blank" style="float: left;margin-top: 5px;margin-left: 1px">《修改密码准则》</a>

                </el-row>
                <div class="dialog-footer custom-footer" >
                    <el-button @click="isModalVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleForgotPassword">提交</el-button>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script   setup>
    import { reactive, ref,computed , onMounted, onUnmounted ,nextTick} from 'vue'
    import { ElMessage,ElForm, ElFormItem ,ElMessageBox} from 'element-plus'
    import { Message } from '@element-plus/icons-vue'
    import { useRoute, useRouter } from "vue-router"
    import request from '../utlis/axios.js'
    import SIdentify from '../component/Sidentify.vue'
    import axios from 'axios';
    import common from '../../src/api/email.js'
    import emailApi from '../api/email.js';

    //去updateRole页面
    const updateRole = () => {
      router.push('/updaterole')
    }

    //跳转到vip登录
    const loginvip = () => {
        router.push('/vipLogin')
    }
    //
    const forgotPasswordForm = reactive({
        email: '', // 根据需要定义其他字段
        userpass: '',
        confirmPassword: '',
        code: '',
        rAgree: false,
    });
    //forgotPasswordForm表单清空函数
    const clearForgotPasswordForm = () => {
        forgotPasswordForm.email = '';
        forgotPasswordForm.userpass = '';
        forgotPasswordForm.confirmPassword = '';
        forgotPasswordForm.code = '';
        forgotPasswordForm.rAgree = false;
    };

    // 发送邮箱验证码的方法
    const disabled = ref(false);
    const msg = ref('点击获取验证码');
    const count = ref(60);
    const timer = ref(null);
    const sendEmailCode = async () => {
        //如果邮箱为空，提示
        const isValid = await validateEmail();
        if (!isValid) return;
        disabled.value = true;
         const requestCodeResponse = await emailApi.getRequestCode(JSON.stringify({ email: forgotPasswordForm.email }));
            if (requestCodeResponse.data.success) {
                const emailCodeResponse = await emailApi.getEmailCode(forgotPasswordForm.email, requestCodeResponse.data.permissionCode);
                if (emailCodeResponse.data.success) {
                    ElMessage.success({
                        title: '邮箱验证码已发送',
                        message: '验证码有效时长5分钟, 失效请重新发送',
                        duration: 10 * 1000
                    });

                }
            }
        startCountdown();
    };
    // 定义validateEmail函数
    const validateEmail = async () => {
        if (!forgotPasswordForm.email) {
            ElMessage.error('请先输入注册邮箱');
            return false;
        }
        // 使用await等待nextTick完成
        await nextTick();
        // 直接访问ref的.value属性来获取email的值
        const isValid = forgotPasswordForm.email && /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(forgotPasswordForm.email);
        return isValid;
    };
    const startCountdown = () => {
        disabled.value = true; // 确保按钮在倒计时开始时被禁用
        timer.value = setInterval(() => {
            count.value--;

            // 更新消息文本
            msg.value = `${count.value}s后重新获取`;

            if (count.value <= 0) {
                // 停止倒计时并重置状态
                clearInterval(timer.value);
                timer.value = null;
                msg.value = '点击获取验证码';
                count.value = 60;
                disabled.value = false;
            }
        }, 1000);
    };

    //-------------验证码部分：
    let identifyCode = ref('') //图形验证码
    let identifyCodes = ref('1234567890abcdefgz') //验证码出现的数字和字母
    //组件挂载
    onMounted(() => {
        identifyCode.value = ''
        makeCode(identifyCodes.value, 4)
    })
    // 生成随机数
    const randomNum = (min, max) => {
        max = max + 1
        return Math.floor(Math.random() * (max - min) + min)
    }
    // 随机生成验证码字符串
    const makeCode = (o, l) => {
        for (let i = 0; i < l; i++) {
            identifyCode.value += o[randomNum(0, o.length)]
        }
    }
    // 更新验证码
    const refreshCode = () => {
        identifyCode.value = ''
        makeCode(identifyCodes.value, 4)
    }
    //-----------------------------

    //----------------------忘记密码部分
    const isModalVisible = ref(false);
    const rAgree = ref(false); // 复选框的状态
    const openForgotPasswordModal = () => {
        isModalVisible.value = true;
    };
    const forgotPasswordRules = {
        //email正则表达式验证
        email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {
                type: 'email',
                message: '请输入正确的邮箱地址',
                trigger: ['blur', 'change'],
            },
        ],
        //新密码6-20位
        userpass: [
            { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{6,20}$/,
            message: '密码需包含至少1个小写字母、1个大写字母、1个数字长度6-20',
            trigger: 'blur' },
        ],
        confirmPassword: [
            { required: true, message: '请再次输入新密码', trigger: 'blur' },
            {
                validator: (rule, value, callback) => {
                    if (value !== forgotPasswordForm.userpass) {
                        callback(new Error('两次输入的密码不一致'))
                    } else {
                        callback()
                    }
                },
                trigger: 'blur',
            },
        ],
        emailcode: [{ required: true, message: '请输入邮箱验证码', trigger: 'blur' }],
        rAgree: [{ required: true, message: '请勾选用户使用准则', trigger: 'change' }],
    };
    const handleForgotPassword = () => {
        if (!rAgree.value) {
            // 如果未同意，则不执行后续操作
            ElMessage.warning('如要修改请先同意用户修改准则')
            return
        }
        //如果表单为空，则不执行后续操作
        if (Object.values(forgotPasswordForm).every((value) => !value)) {
            ElMessage.error('请填写完整信息')
            return
        }
        ElMessageBox.confirm('确定修改吗？', '修改密码', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
            request({
                url: '/update',
                method: 'POST',
                data: forgotPasswordForm
            }).then((response) => {
                    if (response.data.errorCode == 200){
                        // 提交成功或失败后的提示
                        ElMessage({
                            type: 'success',
                            message: '修改成功！',
                        });
                        //    表单清空
                        clearForgotPasswordForm()
                        isModalVisible.value = false; // 关闭模态框
                    }else {
                        ElMessage({
                            type: 'error',
                            message: '修改失败，验证码错误！',
                        });
                    }
                })
        }).catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消提交',
                });
            });
    };
    //-------------------------

    //-------------------------输入框的悬浮样式设计部分
    const router = useRouter()
    const loginFormRef = ref()
    const isLogin = ref(true)
    //toRegister
    //到注册页面
    const toRegister = () => {
        isLogin.value = false
        router.push('/register')
    }
    //    默认登录信息
    const loginForm = reactive({
        username: '',
        userpass: '',
        code:'',
        authority:'',
    })
    //用于用户名的悬浮样式
    const usernameIsFocused = ref(false);
    const usernameSpinWidth = ref('0px');
    const usernameLabelStyles = computed(() => ({
        lineHeight: usernameIsFocused.value || loginForm.username ? '18px' : '60px',
        fontSize: usernameIsFocused.value || loginForm.username ? '18px' : '24px',
        fontWeight: usernameIsFocused.value || loginForm.username ? '100' : '300',
        top: usernameIsFocused.value || loginForm.username ? '0px' : '10px',
    }));
    //用于密码的悬浮样式
    const userpassIsFocused = ref(false);
    const userpassSpinWidth = ref('0px');
    const userpassLabelStyles = computed(() => ({
        lineHeight: userpassIsFocused.value || loginForm.userpass ? '18px' : '60px',
        fontSize: userpassIsFocused.value || loginForm.userpass ? '18px' : '24px',
        fontWeight: userpassIsFocused.value || loginForm.userpass ? '100' : '300',
        top: userpassIsFocused.value || loginForm.userpass ? '0px' : '10px',
    }));
    function usernameOnFocus() {
        usernameIsFocused.value = true;
        usernameSpinWidth.value = '100%';
    }
    function usernameOnBlur() {
        usernameIsFocused.value = false;
        usernameSpinWidth.value = '0px';
    }

    function userpassOnFocus() {
        userpassIsFocused.value = true;
        userpassSpinWidth.value = '100%';
    }
    function userpassOnBlur() {
        userpassIsFocused.value = false;
        userpassSpinWidth.value = '0px';
        if (!loginForm.userpass) {

        }
        if (!validateAndShowMessage('userpass', loginRules.userpass)) {
            // 如果验证失败，可以在这里阻止表单提交或做其他处理
        }
    }
    // 添加验证码输入框聚焦与失焦事件处理
    const codeIsFocused = ref(false);
    const codeSpinWidth = ref('0px');
    const codeLabelStyles = computed(() => ({
        lineHeight: codeIsFocused.value || loginForm.code ? '18px' : '60px',
        fontSize: codeIsFocused.value || loginForm.code ? '18px' : '24px',
        fontWeight: codeIsFocused.value || loginForm.code ? '100' : '300',
        top: codeIsFocused.value || loginForm.code ? '0px' : '10px',
    }));
    function codeOnFocus() {
        codeIsFocused.value = true;
        codeSpinWidth.value = '50%';
    }
    function codeOnBlur() {
        codeIsFocused.value = false;
        codeSpinWidth.value = '0px';
        if (!loginForm.code) {
            // Handle blur logic if needed
        }
    }

    //-------------------------
    //    登录规则校验
    // 定义一个函数来根据规则检查并显示错误消息
    function validateAndShowMessage(fieldName, rules) {
        const fieldValue = loginForm[fieldName];
        const failedRules = rules.filter(rule => {
            if (rule.required && !fieldValue) {
                return true;
            }
            if (rule.min !== undefined && fieldValue.length < rule.min) {
                return true;
            }
            if (rule.max !== undefined && fieldValue.length > rule.max) {
                return true;
            }
            return false;
        });

        if (failedRules.length > 0) {
            // 组合所有失败规则的消息
            const errorMessage = failedRules.map(rule => rule.message).join('，');
                ElMessage({
                    message: `请注意！${errorMessage}`,
                    type: 'error',
                    duration: 5000,
                });

            return false; // 表示验证未通过
        }
        return true; // 验证通过
    }
    const loginRules = reactive({
        username: [
            { required: true, message: '用户名不可为空', trigger: 'blur' },
            { min: 3, max: 20, message: '用户名长度为3-20', trigger: 'blur' },
        ],
        userpass: [
            { required: true, message: '密码不可为空', trigger: 'blur' }
            , { min: 6, max: 20, message: '密码长度为6-20', trigger: 'blur' }
        ]
    })


    //-------------------------
    //    登录请求信息
    const submitForm = (event) => {
        event.preventDefault(); // 阻止表单默认提交行为
        //验证验证码不为空
        if (!loginForm.code) {
            ElMessage({ type: 'error', message: '验证码不能为空！' })
            return
        }
        //验证验证码是否正确
        if (loginForm.code != identifyCode.value) {
            ElMessage({ type: 'error', message: '验证码错误' })
            refreshCode()
            return
        } else {
            loginFormRef.value.validate((valid) => {
                if (valid) {
                    request({
                        url: '/commonLogin',
                        method: 'POST',
                        data: loginForm
                    }).then(res => {
                        if (200 == res.data.errorCode) {
                            sessionStorage.setItem('authority', res.data.data.authority)
                            //邮箱
                            sessionStorage.setItem('email', res.data.data.email)
                            sessionStorage.setItem('loginUser', JSON.stringify(loginForm))
                            //登录成功跳转到HomePage页面
                            router.push('/common')
                            ElMessage({
                                message: '登录成功！',
                                type: 'success',
                            })
                        } else if ("3333" === res.data.errorCode){
                          //账号锁定
                          ElMessage({ message: "该账号被锁定！请联系管理员！", type: 'error' });
                        }else {
                            ElMessage({
                                message: '登录失败,您的用户名或密码错误！',
                                type: 'error',
                            })
                        }
                    })
                } else {
                    ElMessage({
                        message: '账号或者密码格式错误！',
                        type: 'error',
                    })
                }
            })
        }
    }
</script>


<style lang="scss" scoped>
  @import '/src/assets/css/font-awesome-4.7.0/css/font-awesome.min.css';
  @import '/src/assets/css/style.css';
  .disable-click {
    //邮箱
    pointer-events: none;
    cursor: not-allowed;
  }
  .custom-form {
    max-width: 460px;
    padding: 20px;
  }

  .form-item-align {
    display: flex;
    align-items: center;
  }

  .flex-row {
    display: flex;
    align-items: center;
    justify-content: flex-start; /* 保证验证码与输入框左侧对齐 */
  }

  .el-input {
    flex: 1;
  }

  .checkBox {
    margin-bottom: 15px;
  }

  .custom-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
</style>



